<template>
  <div id="pictureUpload">
    <a-upload
      list-type="picture-card"
      :show-upload-list="false"
      :custom-request="handleUpload"
      :before-upload="beforeUpload"
    >
      <img v-if="picture?.url" :src="picture?.url" alt="avatar" />
      <div v-else>
        <loading-outlined v-if="loading"></loading-outlined>
        <plus-outlined v-else></plus-outlined>
        <div class="ant-upload-text">点击或拖拽上传文件</div>
      </div>
    </a-upload>
  </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import type { UploadProps } from 'ant-design-vue';
import {uploadPictureUsingPost} from "@/api/pictureController";

// 由父组件传入参数
interface Props {
  picture?: API.PictureVO,
  spaceId?: number,
  onSuccess?: (newPicture: API.PictureVO) => void
}

// 存储返回参数的值
const props = defineProps<Props>()
// 图片上传前校验和处理逻辑
const beforeUpload = (file: UploadProps['fileList'][number]) => {
  // 设置允许上传的类型
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
  if (!isJpgOrPng) {
    message.error('不支持该类型文件，推荐jpg或png!');
  }
  // 图片大小要小于10M
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    message.error('不能上传超过 10M 的图片!');
  }
  return isJpgOrPng && isLt10M;
};

// 图片上传后至后端的请求逻辑
const loading = ref<boolean>(false);
/**
 * 上传图片到后端
 * @param file
 */
const handleUpload = async ({ file }: any) => {
  loading.value = true;
  try {
    // 得到图片的id，否则空;如果已经有该图片id，则为更新图片操作
    const params: API.PictureUploadRequest = props.picture ? {id: props.picture.id} : {};
    // 获取空间id
    params.spaceId = props.spaceId;
    // 等待前端有数据后调用后端接口
    const res = await uploadPictureUsingPost(params, {}, file);
    // 如果数据存在将图片信息传递给父组件
    if(res.data.code === 0 && res.data.data) {
      message.success('图片上传成功');
      props.onSuccess?.(res.data.data);
    } else {
      message.error('图片上传失败，' + res.data.message);
    }
  } catch (error) {
    message.error('图片上传失败');
  } finally {
    //执行完毕后将loading值设置回来
    loading.value = false;
  }
};

</script>
<style scoped>
#pictureUpload :deep(.ant-upload) {
  width: 100% !important;
  height: 100% !important;
  min-height: 152px;
  min-width: 152px;
}
#pictureUpload img {
  max-width: 100%;
  max-height: 480px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
